#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import struct
import ConfigParser
import os
from ifconfig import ifconfig
import select

MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007

def saveconfig():
	config = ConfigParser.RawConfigParser()
	config.add_section('server')
	config.set('server', 'group', MCAST_GRP)
	config.set('server', 'port', MCAST_PORT)
	# Writing our configuration file to 'example.cfg'
	with open('mcastserver.cfg', 'wb') as configfile:
	    config.write(configfile)

def loadsavedusername():
	global MCAST_GRP;
	global MCAST_PORT;

	config = ConfigParser.RawConfigParser();
	config.read('mcastserver.cfg');

	try:
		print config.get('server', 'group'), config.getint('server','port');

		group = config.get('server', 'group');
		port = config.getint('server', 'port');

		if (len(group) > 0):
			MCAST_GRP = group;

		if (port != 0):
			MCAST_PORT = port;
			
	except:
		print 'exception read config'
		pass;

loadsavedusername();
saveconfig();

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', MCAST_PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)

sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

inputs = [sock]
outputs = []

running = 1

eth0info = ifconfig('eth0')

def getserveraddr():
	global inputs, outputs, running;

	while running:
		try:
			inputready,outputready,exceptready = select.select(inputs, outputs, [], 5)
		except select.error, e:
			break
		except socket.error, e:
			break

		for s in inputready:
			if (s == sock):
				servers = sock.recv(10240)
				#print servers
				if (servers.startswith("SERVER:")):
					return servers[len("SERVER:"):].split(',');

def getdeviceconfig():
	global sock;
	sock.sendto(eth0info['hwaddr'], (MCAST_GRP, MCAST_PORT));
	while running:
		try:
			inputready,outputready,exceptready = select.select(inputs, [], [], 5)
		except select.error, e:
			break
		except socket.error, e:
			break

		for s in inputready:
			if (s == sock):
				servers = sock.recv(10240)
				print servers
				return servers;


print getserveraddr();
print getdeviceconfig();

